import { useEffect, useRef, useState } from 'react'
import { Input, Button, Avatar, message, Tooltip, Spin, Empty, Alert } from 'antd'
import { SendOutlined, MoreOutlined, LoadingOutlined, InfoCircleOutlined, MessageOutlined, ReloadOutlined } from '@ant-design/icons'
import { aiServiceStreamAPI } from '../service/message'
import {getStorage} from '../utils/tools'
import '../utils/AIService.css'

const { TextArea } = Input

const AIService = () => {
  const [messages, setMessages] = useState([
    {
      role: 'assistant',
      content: '欢迎使用北京中关村JSD2506班项目峰会智慧营销平台智能管理客服！',
      id: 'welcome',
      timestamp: new Date().toISOString()
    }
  ])
  const [inputValue, setInputValue] = useState('')
  const [isSending, setIsSending] = useState(false)
  const [isTyping, setIsTyping] = useState(false)
  const [connected, setConnected] = useState(true)
  const [lastError, setLastError] = useState('')
  const messagesEndRef = useRef(null)
  const currentStreamRef = useRef(null)
  const cleanupFunctionsRef = useRef([])

  // 自动滚动到底部
  const scrollToBottom = () => {
    messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' })
  }

  // 处理发送消息
  const handleSendMessage = () => {
    if (!inputValue.trim() || isSending) return

    const userMessage = {
      role: 'user',
      content: inputValue.trim(),
      id: `user_${Date.now()}`,
      timestamp: new Date().toISOString()
    }

    setMessages(prev => [...prev, userMessage])
    setInputValue('')
    setIsSending(true)
    setIsTyping(true)
    setLastError('')

    // 创建助手消息占位符
    const assistantMessageId = `assistant_${Date.now()}`
    const assistantMessage = {
      role: 'assistant',
      content: '',
      id: assistantMessageId,
      timestamp: new Date().toISOString()
    }

    setMessages(prev => [...prev, assistantMessage])

    let accumulatedContent = '';
    let cleanup = null;

    // 停止之前的流（如果有）
    if (currentStreamRef.current) {
      currentStreamRef.current();
      currentStreamRef.current = null;
    }

    const sendRequest = () => {
      try {
        setConnected(true);

        // 调用流式AI服务API
        cleanup = aiServiceStreamAPI(
            inputValue.trim(),
            // 接收数据的回调
            (chunk) => {
              accumulatedContent += chunk;
              // 实时更新助手消息内容
              setMessages(prev => prev.map(msg =>
                  msg.id === assistantMessageId
                      ? { ...msg, content: accumulatedContent }
                      : msg
              ));
            },
            // 错误处理回调
            (error) => {
              console.error('发送消息失败:', error);
              setLastError(error.message);

              // 只有在没有收到任何内容时才显示错误消息
              if (accumulatedContent.length === 0) {
                setMessages(prev => prev.map(msg =>
                    msg.id === assistantMessageId
                        ? { ...msg, content: `抱歉，请求失败: ${error.message}` }
                        : msg
                ));
              }

              setIsSending(false);
              setIsTyping(false);
              setConnected(false);
            },
            // 完成回调
            () => {
              console.log('流式响应完成回调');
              setIsSending(false);
              setIsTyping(false);
              setConnected(true);
              currentStreamRef.current = null;
            }
        );

        // 存储清理函数
        currentStreamRef.current = cleanup;
        registerCleanup(cleanup);

      } catch (error) {
        console.error('发送消息异常:', error);
        setConnected(false);
        setLastError(error.message);
        message.error('发送消息失败，请稍后再试');
        setMessages(prev => prev.map(msg =>
            msg.id === assistantMessageId
                ? { ...msg, content: '抱歉，当前无法连接到AI服务，请检查网络连接或稍后再试。' }
                : msg
        ));
        setIsSending(false);
        setIsTyping(false);
      }
    };

    // 开始发送请求
    sendRequest();
  }

  // 停止当前流式响应
  const handleStopGeneration = () => {
    if (currentStreamRef.current) {
      currentStreamRef.current();
      currentStreamRef.current = null;
      setIsSending(false);
      setIsTyping(false);
      message.info('已停止生成');
    }
  }

  // 注册清理函数
  const registerCleanup = (fn) => {
    if (typeof fn === 'function') {
      cleanupFunctionsRef.current.push(fn);
    }
  };

  // 组件卸载时清理
  useEffect(() => {
    return () => {
      // 执行所有注册的清理函数
      cleanupFunctionsRef.current.forEach(fn => {
        try {
          fn();
        } catch (error) {
          console.error('清理函数执行失败:', error);
        }
      });
      cleanupFunctionsRef.current = [];

      // 停止当前流
      if (currentStreamRef.current) {
        currentStreamRef.current();
        currentStreamRef.current = null;
      }
    };
  }, []);

  // 处理输入框变化
  const handleInputChange = (e) => {
    setInputValue(e.target.value)
  }

  // 处理键盘事件
  const handleKeyPress = (e) => {
    if (e.key === 'Enter' && !e.shiftKey) {
      e.preventDefault()
      handleSendMessage()
    }
  }

  // 滚动到底部
  useEffect(() => {
    scrollToBottom()
  }, [messages])

  // 获取当前用户信息
  const currentUser = {
    name: getStorage('nickname') || '管理员',
    avatar: '👤'
  }

  return (
      <div className="ai-service-container" style={{
        height: '100%',
        display: 'flex',
        flexDirection: 'column',
        backgroundColor: '#f0f2f5',
        borderRadius: '8px',
        overflow: 'hidden',
        boxShadow: '0 2px 8px rgba(0, 0, 0, 0.1)'
      }}>
        {/* 头部 */}
        <div className="ai-service-header" style={{
          padding: '16px 24px',
          backgroundColor: '#667eea',
          color: 'white',
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'space-between',
          borderBottom: '1px solid rgba(255, 255, 255, 0.2)'
        }}>
          <div className="header-left" style={{ display: 'flex', alignItems: 'center', gap: '12px' }}>
            <MessageOutlined style={{ fontSize: '20px' }} />
            <h2 style={{ margin: 0, fontSize: '18px' }}>智能客服</h2>
            <Tooltip title="基于阿里百炼AI">
              <InfoCircleOutlined style={{ fontSize: '14px', cursor: 'pointer' }} />
            </Tooltip>
          </div>
          <div className="header-right" style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
            {isSending && (
                <Button
                    type="text"
                    size="small"
                    onClick={handleStopGeneration}
                    style={{
                      color: 'white',
                      border: '1px solid rgba(255,255,255,0.3)',
                      fontSize: '12px'
                    }}
                >
                  停止生成
                </Button>
            )}
            {!connected && lastError && (
                <Tooltip title={lastError}>
              <span style={{
                fontSize: '12px',
                backgroundColor: 'rgba(255, 255, 255, 0.2)',
                padding: '2px 8px',
                borderRadius: '12px',
                cursor: 'help'
              }}>
                连接异常
              </span>
                </Tooltip>
            )}
            <Button
                type="text"
                icon={<MoreOutlined />}
                style={{ color: 'white' }}
                size="small"
            />
          </div>
        </div>

        {/* 聊天内容区域 */}
        <div className="ai-service-messages" style={{
          flex: 1,
          padding: '20px',
          overflowY: 'auto',
          display: 'flex',
          flexDirection: 'column',
          gap: '16px',
          backgroundColor: '#f0f2f5'
        }}>
          {messages.length === 0 ? (
              <Empty description="暂无消息" style={{ marginTop: '100px' }} />
          ) : (
              messages.map((msg, index) => (
                  <div key={msg.id} className={`message-wrapper ${msg.role}`} style={{
                    display: 'flex',
                    flexDirection: msg.role === 'user' ? 'row-reverse' : 'row',
                    gap: '12px',
                    alignItems: 'flex-start'
                  }}>
                    <Avatar style={{
                      width: '40px',
                      height: '40px',
                      fontSize: '16px',
                      backgroundColor: msg.role === 'user' ? '#4caf50' : '#667eea'
                    }}>
                      {msg.role === 'user' ? currentUser.avatar : 'AI'}
                    </Avatar>
                    <div className="message-content" style={{
                      maxWidth: '70%',
                      padding: '12px 16px',
                      borderRadius: '18px',
                      backgroundColor: msg.role === 'user' ? '#4caf50' : 'white',
                      color: msg.role === 'user' ? 'white' : '#333',
                      boxShadow: '0 1px 3px rgba(0, 0, 0, 0.1)',
                      wordWrap: 'break-word',
                      position: 'relative'
                    }}>
                      <div style={{
                        margin: 0,
                        lineHeight: '1.5',
                        whiteSpace: 'pre-wrap',
                        minHeight: '1em'
                      }}>
                        {msg.content || (msg.role === 'assistant' && isTyping ? '' : msg.content)}
                      </div>
                      <div style={{
                        fontSize: '10px',
                        opacity: 0.6,
                        marginTop: '4px',
                        textAlign: 'right'
                      }}>
                        {new Date(msg.timestamp).toLocaleTimeString()}
                      </div>
                    </div>
                  </div>
              ))
          )}

          {isTyping && (
              <div className="typing-indicator" style={{
                display: 'flex',
                gap: '12px',
                alignItems: 'flex-start',
                paddingLeft: '52px'
              }}>
                <Avatar style={{
                  width: '40px',
                  height: '40px',
                  fontSize: '16px',
                  backgroundColor: '#667eea'
                }}>AI</Avatar>
                <div style={{
                  padding: '12px 16px',
                  borderRadius: '18px',
                  backgroundColor: 'white',
                  boxShadow: '0 1px 3px rgba(0, 0, 0, 0.1)'
                }}>
                  <div style={{ display: 'flex', gap: '4px' }}>
                    <div style={{
                      width: '8px',
                      height: '8px',
                      backgroundColor: '#667eea',
                      borderRadius: '50%',
                      animation: 'typing 1.4s infinite ease-in-out'
                    }}></div>
                    <div style={{
                      width: '8px',
                      height: '8px',
                      backgroundColor: '#667eea',
                      borderRadius: '50%',
                      animation: 'typing 1.4s infinite ease-in-out 0.2s'
                    }}></div>
                    <div style={{
                      width: '8px',
                      height: '8px',
                      backgroundColor: '#667eea',
                      borderRadius: '50%',
                      animation: 'typing 1.4s infinite ease-in-out 0.4s'
                    }}></div>
                  </div>
                </div>
              </div>
          )}

          <div ref={messagesEndRef} />
        </div>

        {/* 输入区域 */}
        <div className="ai-service-input" style={{
          padding: '16px 24px',
          backgroundColor: 'white',
          borderTop: '1px solid #f0f0f0',
          display: 'flex',
          gap: '12px',
          alignItems: 'flex-end'
        }}>
          <TextArea
              value={inputValue}
              onChange={handleInputChange}
              onPressEnter={handleKeyPress}
              placeholder="输入您的问题...\nShift+Enter 换行"
              rows={2}
              maxLength={500}
              style={{
                borderRadius: '20px',
                resize: 'none',
                borderColor: '#d9d9d9'
              }}
              disabled={isSending}
          />
          <Button
              type="primary"
              icon={isSending ? <LoadingOutlined /> : <SendOutlined />}
              onClick={isSending ? handleStopGeneration : handleSendMessage}
              disabled={!inputValue.trim() && !isSending}
              style={{
                borderRadius: '50%',
                minWidth: '44px',
                height: '44px',
                backgroundColor: isSending ? '#ff4d4f' : '#667eea',
                borderColor: isSending ? '#ff4d4f' : '#667eea'
              }}
          />
        </div>
      </div>
  )
}

export default AIService